<?php
require 'vendor/autoload.php';

use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\IOFactory;

function buildComparisonRows($deliverPhotoExifs,$contrastPhotoExifs) {
    $rows = [];
    foreach ($deliverPhotoExifs as $d) {
    	if (empty($d['FileName']))continue;
        $fileName = $d['FileName'];
        // 不转换，直接使用原始 DateTime 字符串
        $deliverDT  = (string)($d['DateTime'] ?? '');
        $c          = $contrastPhotoExifs[$fileName] ?? [];
        $contrastDT = (string)($c['DateTime'] ?? '');
        // 第四列：对比片所在“文件夹”——按你的要求直接 basename(CUSTOM_REAL_PATH)
        $contrastFolder = '';
        if (!empty($c['CUSTOM_REAL_PATH'])) {
            $contrastFolder = basename(dirname($c['CUSTOM_REAL_PATH']));
        }
        $rows[] = [
            'FileName'         => $fileName,
            'DeliverDateTime'  => $deliverDT,
            'ContrastDateTime' => $contrastDT,
            'ContrastFolder'   => $contrastFolder,
        ];
    }
    return $rows;
}

/** 生成 Word（四列表格，原样显示 DateTime） */
function buildCompareWord(string $outputDocx, array $rows): void {
    $phpWord = new PhpWord();
    $phpWord->setDefaultFontName('Microsoft YaHei');
    $phpWord->setDefaultFontSize(10);
    $section = $phpWord->addSection([
        'orientation' => 'portrait',
        'marginLeft'  => 800, 'marginRight' => 800,
        'marginTop'   => 800, 'marginBottom'=> 800,
    ]);
    $section->addText('照片时间对比（交付 vs 对比）', ['bold'=>true,'size'=>14]);
    $section->addTextBreak(1);
    $table = $section->addTable([
        'borderSize' => 6,
        'borderColor'=> 'cccccc',
        'cellMargin' => 60,
        'width'      => 100 * 50,
        'unit'       => \PhpOffice\PhpWord\SimpleType\TblWidth::PERCENT,
    ]);
    // 表头
    $table->addRow();
    foreach (['文件名','对比片所在文件夹','对比片 DateTime','交付片 DateTime'] as $th) {
        $table->addCell()->addText($th, ['bold'=>true]);
    }
    // 行
    foreach ($rows as $row) {
        $table->addRow();
        $table->addCell()->addText($row['FileName']);
        $table->addCell()->addText($row['ContrastFolder']);
        $table->addCell()->addText($row['ContrastDateTime']);
        $table->addCell()->addText($row['DeliverDateTime']);
    }
    IOFactory::createWriter($phpWord, 'Word2007')->save($outputDocx);
}

//获取图片的exif信息
function getPhotoExif($photoPath){
	if (preg_match('/\.(jpg|jpeg|png|gif|webp)$/i', $photoPath)) {
		$exif = @exif_read_data($photoPath);
		if (!empty($exif['DateTime'])) {
			$exif["CUSTOM_REAL_PATH"] = $photoPath;
			return $exif;
		}
	}
	return [];
}
//获取所有图片的EXIF信息
function getPhotoExifs($photoPaths){
	$exifs = [];
	foreach ($photoPaths as $key => $photoPath) {
		$exif = getPhotoExif($photoPath);
		if (!empty($exif)) {
			$exifs[] = $exif;
		}	
	}
	return $exifs;
}

//获取照片文件夹基础目录
$baseDir = dirname(__FILE__,2).DIRECTORY_SEPARATOR."照片".DIRECTORY_SEPARATOR;
$contrastPhotoDir = $baseDir."对照".DIRECTORY_SEPARATOR;
$deliverPhotoDir = $baseDir."交付".DIRECTORY_SEPARATOR;
//文件夹是否存在
if (!is_dir($contrastPhotoDir)) exit("对照照片文件夹不存在");
if (!is_dir($deliverPhotoDir)) exit("交付照片文件夹不存在");
//获取对照文件夹中的多个对比文件夹
$contrastPhotoDirs = glob($contrastPhotoDir."*",GLOB_ONLYDIR);
if (empty($contrastPhotoDirs)) exit("对照照片文件夹不存在");
//获取交付照片的exif信息
$deliverPhotoPaths = glob($deliverPhotoDir."*");
if (empty($deliverPhotoPaths)) exit("交付照片文件夹不能为空");
$deliverPhotoExifs = getPhotoExifs($deliverPhotoPaths);
//对交付照片的exif信息按照DateTime进行排序
usort($deliverPhotoExifs, function($a, $b) {
	$aTimeStamp = strtotime($a['DateTime']??"");
	$bTimeStamp = strtotime($b['DateTime']??"");
    if ( $aTimeStamp == $bTimeStamp) return 0;
    return ($aTimeStamp < $bTimeStamp) ? -1 : 1;
});
//获取对比照片的EXIF信息
$contrastPhotoExifs = array_reduce($deliverPhotoExifs, function($carry,$deliverPhotoExif)use($contrastPhotoDirs){
	$fileName = $deliverPhotoExif['FileName']??"";
	foreach($contrastPhotoDirs as $contrastPhotoDir){
		$contrastPhotoPath = $contrastPhotoDir.DIRECTORY_SEPARATOR.$fileName;
		if (is_file($contrastPhotoPath) && !empty($exif = getPhotoExif($contrastPhotoPath))) {
			$carry[$fileName] = $exif;
		}
	}
	return $carry;
},[]);
$rows = buildComparisonRows($deliverPhotoExifs, $contrastPhotoExifs);
buildCompareWord (__DIR__.DIRECTORY_SEPARATOR.date("YmdHis")."照片时间线对比.docx",  $rows);
echo "OK：已生成Word表格。\n";